<template>
  <view class="checkin-page" :class="{'no-scroll': showFeePopup || showAddElder}">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="back-btn" @tap="goBack">
        <text class="iconfont">&#xe60e;</text>
      </view>
      <view class="page-title">申请入住</view>
      <view class="placeholder"></view>
    </view>
    
    <!-- 养老院信息卡片 -->
    <view class="home-card">
      <view class="home-name">{{ nursingHomeName }}</view>
      <view class="address-row">
        <text class="iconfont address-icon">&#xe614;</text>
        <text class="address-text">{{ nursingHomeAddress }}</text>
      </view>
    </view>
    
    <!-- 入住人选择器 -->
    <view class="resident-selector">
      <scroll-view class="selector-scroll" scroll-x="true" show-scrollbar="false">
        <view 
          class="resident-item" 
          v-for="(person, index) in elderOptions" 
          :key="index"
          :class="{ 'active': checkinData.elderId === person.id }"
          @tap="switchResident(person)"
        >
          <view class="resident-avatar">
            <image :src="person.avatar || '../../image/R.jpg'" mode="aspectFill"></image>
          </view>
          <text class="resident-name">{{ person.name }}</text>
        </view>
        <view class="resident-item add-item" @tap="showAddElderPopup">
          <view class="add-avatar">
            <text class="iconfont">&#xe654;</text>
          </view>
          <text class="resident-name">添加</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 表单区域 -->
    <scroll-view class="form-scroll" scroll-y="true">
      <view class="form-container">
        <!-- 基本信息部分 -->
        <view class="form-section">
          <view class="section-title">
            <text class="title-text">基本信息</text>
          </view>
          
          <!-- 紧急联系人 -->
          <view class="form-item">
            <view class="label required">紧急联系人</view>
            <view class="input-wrapper">
              <input 
                type="text" 
                v-model="checkinData.emergencyContact" 
                placeholder="请输入紧急联系人姓名" 
                placeholder-class="placeholder"
                class="input"
                maxlength="10"
              />
              <text class="iconfont input-icon">&#xe60d;</text>
            </view>
          </view>
          
          <!-- 联系电话 -->
          <view class="form-item">
            <view class="label required">联系电话</view>
            <view class="input-wrapper">
              <input 
                type="number" 
                v-model="checkinData.emergencyPhone" 
                placeholder="请输入紧急联系人电话" 
                placeholder-class="placeholder"
                class="input"
                maxlength="11"
              />
              <text class="iconfont input-icon">&#xe638;</text>
            </view>
          </view>
          
          <!-- 入住日期 -->
          <view class="form-item">
            <view class="label required">入住日期</view>
            <view class="input-wrapper">
              <picker 
                mode="date"
                :value="checkinData.checkinDate"
                :start="startDate"
                :end="endDate"
                @change="onDateChange"
                fields="day"
                :disabled="showAddElder"
              >
                <view class="picker-value" @tap="openDatePicker">
                  <text v-if="!checkinData.checkinDate" class="placeholder-text">请选择入住日期</text>
                  <text v-else class="value-text">{{ formatDisplayDate(checkinData.checkinDate) }}</text>
                  <text class="iconfont calendar-icon">&#xe62d;</text>
                </view>
              </picker>
            </view>
          </view>
          
          <!-- 备注信息 -->
          <view class="form-item">
            <view class="label">备注</view>
            <view class="input-wrapper">
              <textarea 
                v-model="checkinData.remark" 
                placeholder="请输入备注信息（选填）" 
                placeholder-class="placeholder"
                class="textarea"
                maxlength="200"
              ></textarea>
            </view>
          </view>
        </view>
        
        <!-- 收费选项部分 -->
        <view class="form-section">
          <view class="section-title">
            <text class="title-text">收费选项</text>
          </view>
          
          <view class="fee-options">
            <!-- 房型选择按钮 -->
            <view class="fee-option-btn" @tap="openFeePopup('rooms')">
              <view class="option-icon room-icon">
                <text class="iconfont">&#xe60b;</text>
              </view>
              <view class="option-info">
                <view class="option-name required">房型</view>
                <view class="option-status">{{ checkinData.selectedRoom !== null ? feeOptions.rooms[checkinData.selectedRoom].name : '请选择' }}</view>
              </view>
            </view>
            
            <!-- 伙食选择按钮 -->
            <view class="fee-option-btn" @tap="openFeePopup('food')">
              <view class="option-icon food-icon">
                <text class="iconfont">&#xe611;</text>
              </view>
              <view class="option-info">
                <view class="option-name">伙食</view>
                <view class="option-status">{{ checkinData.selectedFood.length > 0 ? `已选${checkinData.selectedFood.length}项` : '未选择' }}</view>
              </view>
            </view>
            
            <!-- 特殊服务按钮 -->
            <view class="fee-option-btn" @tap="openFeePopup('special')">
              <view class="option-icon special-icon">
                <text class="iconfont">&#xe618;</text>
              </view>
              <view class="option-info">
                <view class="option-name">特殊</view>
                <view class="option-status">{{ checkinData.selectedSpecial.length > 0 ? `已选${checkinData.selectedSpecial.length}项` : '未选择' }}</view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 费用总结 -->
        <view class="price-summary">
          <view class="summary-title">费用总结</view>
          <view class="summary-list">
            <view class="summary-item" v-if="checkinData.selectedRoom !== null">
              <text class="item-name">{{ feeOptions.rooms[checkinData.selectedRoom].name }}</text>
              <text class="item-price">¥{{ feeOptions.rooms[checkinData.selectedRoom].price }}/{{ feeOptions.rooms[checkinData.selectedRoom].period }}</text>
            </view>
            
            <view class="summary-item" v-for="(foodIndex, i) in checkinData.selectedFood" :key="'food-sum-'+i">
              <text class="item-name">{{ feeOptions.food[foodIndex].name }}</text>
              <text class="item-price">¥{{ feeOptions.food[foodIndex].price }}/{{ feeOptions.food[foodIndex].period }}</text>
            </view>
            
            <view class="summary-item" v-for="(specialIndex, i) in checkinData.selectedSpecial" :key="'special-sum-'+i">
              <text class="item-name">{{ feeOptions.special[specialIndex].name }}</text>
              <text class="item-price">¥{{ feeOptions.special[specialIndex].price }}/{{ feeOptions.special[specialIndex].period }}</text>
            </view>
            
            <view class="summary-divider"></view>
            
            <view class="total-price">
              <text class="total-label">月费用预估：</text>
              <text class="total-value">¥{{ totalMonthlyPrice }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部提交按钮 -->
    <view class="bottom-bar">
      <view class="submit-btn" :class="{ 'active': isFormValid }" @tap="submitCheckin">
        <text>提交申请</text>
      </view>
    </view>

    <!-- 新增入住人弹窗 -->
    <view v-if="showAddElder" class="add-elder-popup">
      <view class="popup-mask" @tap.stop.prevent="safeHideAddElderPopup"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">新增入住人</text>
          <view class="close-btn" @tap.stop.prevent="safeHideAddElderPopup">
            <text class="iconfont">&#xe60e;</text>
          </view>
        </view>
        <view class="popup-body">
          <!-- 头像上传 -->
          <view class="avatar-selector">
            <view class="avatar-preview" @tap.stop="chooseAvatar">
              <image v-if="newElder.avatar" :src="newElder.avatar" mode="aspectFill"></image>
              <image v-else src="../../image/R.jpg" mode="aspectFill"></image>
              <view class="avatar-mask">
                <text class="iconfont">&#xe654;</text>
              </view>
            </view>
            <text class="avatar-tip">点击更换头像</text>
          </view>
          
          <view class="popup-form-item">
            <view class="popup-label required">姓名</view>
            <input type="text" v-model="newElder.name" placeholder="请输入入住人姓名" class="popup-input" maxlength="10" />
          </view>
          
          <view class="popup-form-item">
            <view class="popup-label required">身份证号</view>
            <input type="idcard" v-model="newElder.idCard" placeholder="请输入身份证号" class="popup-input" />
          </view>
          
          <view class="popup-form-item">
            <view class="popup-label required">性别</view>
            <radio-group @change="onGenderChange" class="radio-group">
              <label class="radio-label">
                <radio value="男" :checked="newElder.gender === '男'" color="#2c7873" />
                <text>男</text>
              </label>
              <label class="radio-label">
                <radio value="女" :checked="newElder.gender === '女'" color="#2c7873" />
                <text>女</text>
              </label>
            </radio-group>
          </view>
          
          <view class="popup-form-item">
            <view class="popup-label required">出生日期</view>
            <picker class="popup-picker" mode="date" :value="newElder.birthDate" @change="onBirthDateChange">
              <view class="picker-inner">
                <text v-if="newElder.birthDate" class="value-text">{{ newElder.birthDate }}</text>
                <text v-else class="placeholder-text">请选择出生日期</text>
                <text class="iconfont arrow-icon">&#xe65a;</text>
              </view>
            </picker>
          </view>
          
          <view class="popup-form-item">
            <view class="popup-label required">手机号</view>
            <input type="number" v-model="newElder.phone" placeholder="请输入联系电话" class="popup-input" maxlength="11" />
          </view>
          
          <view class="popup-form-item relation-item">
            <view class="popup-label required">与账号关系</view>
            <picker 
              @change="onRelationChange" 
              :value="relationIndex" 
              :range="relationOptions" 
              range-key="label" 
              class="relation-picker" 
              mode="selector"
            >
              <view class="popup-picker">
                <text v-if="newElder.relation" class="value-text">{{ newElder.relation }}</text>
                <text v-else class="placeholder-text">请选择与账号关系</text>
                <text class="iconfont arrow-icon">&#xe65a;</text>
              </view>
            </picker>
          </view>
        </view>
        <view class="popup-footer">
          <view class="cancel-btn" @tap.stop="safeHideAddElderPopup">
            <text>取消</text>
          </view>
          <view class="confirm-btn" :class="{ 'active': isNewElderValid }" @tap.stop="addNewElder">
            <text>确认</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 费用选项弹窗 -->
    <view class="fee-popup" v-if="showFeePopup">
      <view class="popup-mask" @tap="cancelFeeSelection"></view>
      <view class="popup-content" :class="'popup-' + currentFeeType">
        <view class="popup-header">
          <text class="popup-title">{{ feePopupTitle }}</text>
          <view class="close-btn" @tap="cancelFeeSelection">
            <text class="iconfont">&#xe60e;</text>
          </view>
        </view>
        
        <scroll-view class="popup-body" scroll-y="true">
          <!-- 房型选择内容 -->
          <view class="option-list" v-if="currentFeeType === 'rooms'">
            <view 
              v-for="(item, index) in feeOptions.rooms" 
              :key="'room-popup-'+index"
              class="option-item" 
              :class="{ 'selected': tempSelectedRoom === index }"
              @tap="selectTempRoom(index)"
            >
              <view class="option-content">
                <view class="option-name">{{ item.name }}</view>
                <view class="option-price">¥{{ item.price }}<text class="price-unit">/{{ item.period }}</text></view>
              </view>
              <view class="option-check">
                <text v-if="tempSelectedRoom === index" class="iconfont check-icon">&#xe600;</text>
              </view>
            </view>
          </view>
          
          <!-- 伙食选择内容 -->
          <view class="option-list" v-if="currentFeeType === 'food'">
            <view 
              v-for="(item, index) in feeOptions.food" 
              :key="'food-popup-'+index"
              class="option-item" 
              :class="{ 'selected': tempSelectedFood.includes(index) }"
              @tap="toggleTempFood(index)"
            >
              <view class="option-content">
                <view class="option-name">{{ item.name }}</view>
                <view class="option-price">¥{{ item.price }}<text class="price-unit">/{{ item.period }}</text></view>
                <view class="option-note">{{ item.note }}</view>
              </view>
              <view class="option-check">
                <text v-if="tempSelectedFood.includes(index)" class="iconfont check-icon">&#xe600;</text>
              </view>
            </view>
          </view>
          
          <!-- 特殊服务内容 -->
          <view class="option-list" v-if="currentFeeType === 'special'">
            <view 
              v-for="(item, index) in feeOptions.special" 
              :key="'special-popup-'+index"
              class="option-item" 
              :class="{ 'selected': tempSelectedSpecial.includes(index) }"
              @tap="toggleTempSpecial(index)"
            >
              <view class="option-content">
                <view class="option-name">{{ item.name }}</view>
                <view class="option-price">¥{{ item.price }}<text class="price-unit">/{{ item.period }}</text></view>
                <view class="option-note">{{ item.note }}</view>
              </view>
              <view class="option-check">
                <text v-if="tempSelectedSpecial.includes(index)" class="iconfont check-icon">&#xe600;</text>
              </view>
            </view>
          </view>
        </scroll-view>
        
        <view class="popup-footer">
          <view class="cancel-btn" @tap="cancelFeeSelection">
            <text>取消</text>
          </view>
          <view class="confirm-btn" @tap="confirmFeeSelection">
            <text>确认</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';

// 养老院信息
const nursingHomeId = ref('');
const nursingHomeName = ref('阳光养老院');
const nursingHomeAddress = ref('北京市海淀区西三旗建材城西路88号');

// 老人选项
const elderOptions = ref([
  { id: '1', name: '张爷爷', age: 75, gender: '男' },
  { id: '2', name: '李奶奶', age: 72, gender: '女' },
  { id: '3', name: '王伯伯', age: 80, gender: '男' }
]);
const elderIndex = ref(0);

// 入住申请数据
const checkinData = reactive({
  elderName: '',
  elderId: '',
  emergencyContact: '',
  emergencyPhone: '',
  checkinDate: '',
  relation: '', // 与入住人关系
  relationCode: '',
  selectedRoom: null,
  selectedFood: [],
  selectedSpecial: [],
  remark: ''
});

// 新增入住人弹窗控制
const showAddElder = ref(false);
const newElder = reactive({
  name: '',
  idCard: '',
  birthDate: '',
  gender: '男',
  phone: '',
  avatar: '',
  relation: '',
  relationCode: ''
});

// 费用选项
const feeOptions = reactive({
  rooms: [
    { name: '单人间', price: '4500', period: '月', note: '独立卫浴' },
    { name: '双人间', price: '3200', period: '月', note: '共享卫浴' },
    { name: '三人间', price: '2600', period: '月', note: '共享卫浴' },
    { name: '四人间', price: '2000', period: '月', note: '共享卫浴' }
  ],
  food: [
    { name: '三餐', price: '2000', period: '月', note: '管饱但不提供早餐' },
    { name: '营养套餐', price: '2800', period: '月', note: '专业营养师配餐' },
    { name: '特殊膳食', price: '3200', period: '月', note: '适合慢性病患者' }
  ],
  special: [
    { name: '24小时护理', price: '3000', period: '月', note: '专业护理人员' },
    { name: '康复理疗', price: '1500', period: '月', note: '每周3次' },
    { name: '心理咨询', price: '1200', period: '月', note: '每周1次' },
    { name: '接送服务', price: '800', period: '月', note: '每周1次' }
  ]
});

// 关系选项
const relationOptions = [
  { label: '本人', value: '本人', code: 1 },
  { label: '父亲', value: '父亲', code: 2 },
  { label: '母亲', value: '母亲', code: 3 },
  { label: '配偶', value: '配偶', code: 4 },
  { label: '其他', value: '其他', code: 5 }
];

// 日期范围 - 今天到未来60天
const today = new Date();
const startDate = computed(() => {
  return formatDate(today);
});
const endDate = computed(() => {
  const futureDate = new Date();
  futureDate.setDate(today.getDate() + 60);
  return formatDate(futureDate);
});

// 计算月费用总价
const totalMonthlyPrice = computed(() => {
  let total = 0;
  
  // 房型费用
  if (checkinData.selectedRoom !== null) {
    total += Number(feeOptions.rooms[checkinData.selectedRoom].price);
  }
  
  // 伙食费用
  checkinData.selectedFood.forEach(index => {
    total += Number(feeOptions.food[index].price);
  });
  
  // 特殊服务费用
  checkinData.selectedSpecial.forEach(index => {
    total += Number(feeOptions.special[index].price);
  });
  
  return total.toLocaleString();
});

// 表单是否有效
const isFormValid = computed(() => {
  return checkinData.elderName && 
         checkinData.emergencyContact && 
         /^1\d{10}$/.test(checkinData.emergencyPhone) && 
         checkinData.checkinDate && 
         checkinData.selectedRoom !== null;
});

// 新增入住人有效性验证
const isNewElderValid = computed(() => {
  return newElder.name && 
    validateIdCard(newElder.idCard) && 
    newElder.birthDate && 
    newElder.gender &&
    validatePhone(newElder.phone) &&
    newElder.relation;
});

// 验证身份证号
const validateIdCard = (idCard) => {
  // 简单验证，实际应用中可以使用更复杂的验证规则
  const pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return pattern.test(idCard);
};

// 验证手机号
const validatePhone = (phone) => {
  // 简单验证，实际应用中可以使用更复杂的验证规则
  const pattern = /(^\d{11}$)/;
  return pattern.test(phone);
};

// 费用选项弹窗控制
const showFeePopup = ref(false);
const currentFeeType = ref('');
const tempSelectedRoom = ref(null);
const tempSelectedFood = ref([]);
const tempSelectedSpecial = ref([]);

const feePopupTitle = computed(() => {
  switch (currentFeeType.value) {
    case 'rooms':
      return '选择房型（单选）';
    case 'food':
      return '选择伙食（可多选）';
    case 'special':
      return '选择特殊服务（可多选）';
    default:
      return '';
  }
});

// 控制入住日期弹窗显示
const datePickerVisible = ref(false);

// 监听新增入住人弹窗状态，动态调整日期选择器显示
watch(showAddElder, (newVal) => {
  if (newVal) {
    // 如果新增入住人弹窗打开，确保日期选择器隐藏
    datePickerVisible.value = false;
    
    // 添加阻止默认日期选择器打开的处理
    const pageElements = document.querySelectorAll('.checkin-page');
    pageElements.forEach(el => {
      el.addEventListener('click', preventDatePickerOpen, true);
    });
  } else {
    // 如果新增入住人弹窗关闭，移除阻止事件
    const pageElements = document.querySelectorAll('.checkin-page');
    pageElements.forEach(el => {
      el.removeEventListener('click', preventDatePickerOpen, true);
    });
  }
});

// 阻止日期选择器打开的函数
const preventDatePickerOpen = (e) => {
  if (e.target.closest('uni-picker[mode="date"]') && showAddElder.value) {
    e.stopPropagation();
    e.preventDefault();
    return false;
  }
};

// 日期选择事件
const onDateChange = (e) => {
  checkinData.checkinDate = e.detail.value;
  datePickerVisible.value = false;
};

// 安全打开日期选择器
const openDatePicker = () => {
  if (!showAddElder.value) {
    datePickerVisible.value = true;
  }
};

// 页面加载
onMounted(() => {
  console.log('页面加载完成，检查入住人数据');
  
  // 设置uni-app特定的日期选择器阻止处理
  setupPickerPreventionInUniApp();
  
  // 修复：使用uni.getStorageSync获取页面参数，或者提供默认值
  let params = {};
  try {
    // 尝试从页面参数中获取数据
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    if (currentPage && currentPage.$page && currentPage.$page.options) {
      params = currentPage.$page.options;
    } else if (uni.getStorageSync('nursingHomeParams')) {
      // 如果没有页面参数，尝试从本地存储获取
      params = JSON.parse(uni.getStorageSync('nursingHomeParams'));
    }
  } catch (e) {
    console.error('获取页面参数失败:', e);
  }
    
  // 使用安全的方式获取参数或提供默认值
  nursingHomeId.value = params.id || '1';
  nursingHomeName.value = params.name || '阳光养老院';
  nursingHomeAddress.value = params.address || '北京市海淀区西三旗建材城西路88号';
  
  // 获取已有入住人信息
  getElderOptions();
  
  // 测试弹窗功能
  uni.nextTick(() => {
    console.log('页面渲染完成，检查弹窗控制状态', showAddElder.value);
  });
});

// 设置uni-app特定的日期选择器阻止处理
const setupPickerPreventionInUniApp = () => {
  try {
    // 确保uni对象存在
    if (typeof uni !== 'undefined') {
      // 重写picker的显示方法
      const originalShowPicker = uni.showPicker;
      if (originalShowPicker) {
        uni.showPicker = function(...args) {
          // 如果弹窗已打开，拦截picker显示
          if (showAddElder.value) {
            console.log('阻止日期选择器显示，因为弹窗已打开');
            return;
          }
          // 否则正常显示
          return originalShowPicker.apply(this, args);
        };
      }
    }
  } catch (error) {
    console.error('设置日期选择器阻止处理失败', error);
  }
};

// 安全关闭新增入住人弹窗
const safeHideAddElderPopup = () => {
  // 先临时增加页面层级，避免可能的picker冲突
  const pageEl = document.querySelector('.checkin-page');
  if (pageEl) {
    pageEl.style.zIndex = '999999';
    // 延时降回正常层级
    setTimeout(() => {
      pageEl.style.zIndex = '1';
    }, 500);
  }
  
  // 调用标准关闭方法
  hideAddElderPopup();
};

// 更新hideAddElderPopup引用
const hideAddElderPopup = () => {
  showAddElder.value = false;
  // 恢复页面滚动
  document.body.style.overflow = '';
  
  // 防止可能的uni-picker弹出
  if (typeof uni !== 'undefined' && uni.hideKeyboard) {
    uni.hideKeyboard();
  }
  
  // 解决日期选择器层级问题：延时重置样式以避免冲突
  setTimeout(() => {
    // 重置表单
    Object.assign(newElder, {
      name: '',
      idCard: '',
      birthDate: '',
      gender: '男',
      phone: '',
      avatar: '',
      relation: '',
      relationCode: ''
    });
    // 重置关系选择索引
    relationIndex.value = 0;
  }, 300);
};

// 性别选择改变
const onGenderChange = (e) => {
  newElder.gender = e.detail.value;
};

// 出生日期选择改变
const onBirthDateChange = (e) => {
  newElder.birthDate = e.detail.value;
};

// 添加新入住人
const addNewElder = () => {
  // 表单验证
  if (!isNewElderValid.value) {
    if (!newElder.name) {
      return uni.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
    }
    
    if (!newElder.idCard || !validateIdCard(newElder.idCard)) {
      return uni.showToast({
        title: '请输入有效的身份证号',
        icon: 'none'
      });
    }
    
    if (!newElder.birthDate) {
      return uni.showToast({
        title: '请选择出生日期',
        icon: 'none'
      });
    }
    
    if (!newElder.phone || !validatePhone(newElder.phone)) {
      return uni.showToast({
        title: '请输入有效的手机号',
        icon: 'none'
      });
    }
    
    if (!newElder.relation) {
      return uni.showToast({
        title: '请选择与入住人关系',
        icon: 'none'
      });
    }
  }
  
  // 计算年龄（根据身份证或出生日期）
  const age = calculateAgeFromBirthDate(newElder.birthDate);
  
  // 创建新入住人对象
  const elder = {
    id: Date.now().toString(), // 生成临时ID
    name: newElder.name,
    idCard: newElder.idCard,
    birthDate: newElder.birthDate,
    gender: newElder.gender,
    phone: newElder.phone,
    avatar: newElder.avatar || '',
    relation: newElder.relation,
    relationCode: newElder.relationCode,
    age: age
  };
  
  // 保存到本地存储
  try {
    let storedElders = uni.getStorageSync('residents') || [];
    storedElders.push(elder);
    uni.setStorageSync('residents', storedElders);
    
    // 添加到当前选项
    elderOptions.value.push(elder);
    
    // 自动选择新添加的入住人
    elderIndex.value = elderOptions.value.length - 1;
    checkinData.elderId = elder.id;
    checkinData.elderName = elder.name;
    
    // 提示成功
    uni.showToast({
      title: '添加成功',
      icon: 'success'
    });
    
    // 关闭弹窗
    safeHideAddElderPopup();
  } catch (e) {
    console.error('保存入住人信息失败', e);
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 老人选择改变
const onElderChange = (e) => {
  const index = e.detail.value;
  elderIndex.value = index;
  checkinData.elderId = elderOptions.value[index].id;
  checkinData.elderName = elderOptions.value[index].name;
};

// 切换入住人
const switchResident = (person) => {
  console.log('切换入住人:', person);
  checkinData.elderId = person.id;
  checkinData.elderName = person.name;
  
  // 查找对应的索引
  const index = elderOptions.value.findIndex(item => item.id === person.id);
  if (index !== -1) {
    elderIndex.value = index;
  }
};

// 格式化显示日期
const formatDisplayDate = (dateStr) => {
  if (!dateStr) return '';
  const parts = dateStr.split('-');
  return `${parts[0]}年${parts[1]}月${parts[2]}日`;
};

// 打开费用选择弹窗
const openFeePopup = (type) => {
  currentFeeType.value = type;
  
  // 初始化临时选择的值
  if (type === 'rooms') {
    tempSelectedRoom.value = checkinData.selectedRoom;
  } else if (type === 'food') {
    tempSelectedFood.value = [...checkinData.selectedFood];
  } else if (type === 'special') {
    tempSelectedSpecial.value = [...checkinData.selectedSpecial];
  }
  
  showFeePopup.value = true;
  // 禁止页面滚动
  document.body.style.overflow = 'hidden';
};

// 临时选择房型
const selectTempRoom = (index) => {
  tempSelectedRoom.value = index;
};

// 临时切换伙食选择
const toggleTempFood = (index) => {
  const existingIndex = tempSelectedFood.value.indexOf(index);
  if (existingIndex === -1) {
    tempSelectedFood.value.push(index);
  } else {
    tempSelectedFood.value.splice(existingIndex, 1);
  }
};

// 临时切换特殊服务选择
const toggleTempSpecial = (index) => {
  const existingIndex = tempSelectedSpecial.value.indexOf(index);
  if (existingIndex === -1) {
    tempSelectedSpecial.value.push(index);
  } else {
    tempSelectedSpecial.value.splice(existingIndex, 1);
  }
};

// 取消选择，关闭弹窗
const cancelFeeSelection = () => {
  showFeePopup.value = false;
  // 恢复页面滚动
  document.body.style.overflow = '';
};

// 确认选择
const confirmFeeSelection = () => {
  if (currentFeeType.value === 'rooms') {
    checkinData.selectedRoom = tempSelectedRoom.value;
  } else if (currentFeeType.value === 'food') {
    checkinData.selectedFood = [...tempSelectedFood.value];
  } else if (currentFeeType.value === 'special') {
    checkinData.selectedSpecial = [...tempSelectedSpecial.value];
  }
  
  showFeePopup.value = false;
  // 恢复页面滚动
  document.body.style.overflow = '';
};

// 选择与入住人关系
const relationIndex = ref(0);
const onRelationChange = (e) => {
  console.log('选择关系:', e.detail.value);
  const index = e.detail.value;
  relationIndex.value = index;
  const selectedRelation = relationOptions[index];
  newElder.relation = selectedRelation.label;
  newElder.relationCode = selectedRelation.code;
  
  // 延时300ms，防止拾取器被底部操作栏遮挡
  setTimeout(() => {
    // 触发UI渲染更新
    if (document.activeElement) {
      document.activeElement.blur();
    }
  }, 300);
};

// 提交申请
const submitCheckin = () => {
  // 表单验证
  if (!checkinData.elderName) {
    return uni.showToast({
      title: '请选择入住人',
      icon: 'none'
    });
  }
  
  if (!checkinData.emergencyContact) {
    return uni.showToast({
      title: '请输入紧急联系人',
      icon: 'none'
    });
  }
  
  if (!checkinData.emergencyPhone || !/^1\d{10}$/.test(checkinData.emergencyPhone)) {
    return uni.showToast({
      title: '请输入正确的联系电话',
      icon: 'none'
    });
  }
  
  if (!checkinData.checkinDate) {
    return uni.showToast({
      title: '请选择入住日期',
      icon: 'none'
    });
  }
  
  if (checkinData.selectedRoom === null) {
    return uni.showToast({
      title: '请选择房型',
      icon: 'none'
    });
  }
  
  // 提交数据
  console.log('提交入住申请数据', {
    nursingHomeId: nursingHomeId.value,
    ...checkinData,
    room: feeOptions.rooms[checkinData.selectedRoom].name,
    foods: checkinData.selectedFood.map(i => feeOptions.food[i].name),
    specialServices: checkinData.selectedSpecial.map(i => feeOptions.special[i].name),
    totalPrice: totalMonthlyPrice.value,
    remark: checkinData.remark || '无'
  });
  
  // 模拟提交成功
  uni.showLoading({
    title: '提交中...'
  });
  
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '申请提交成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
      }
    });
  }, 1500);
};

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      newElder.avatar = res.tempFilePaths[0];
    },
    fail: (err) => {
      console.error('选择头像失败', err);
      uni.showToast({
        title: '选择头像失败',
        icon: 'none'
      });
    }
  });
};

// 根据出生日期计算年龄
const calculateAgeFromBirthDate = (birthDateString) => {
  const today = new Date();
  const birthDate = new Date(birthDateString);
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age;
};

// 获取入住人选项
const getElderOptions = () => {
  // 实际项目中应该从服务器或本地存储获取
  try {
    // 从本地存储获取入住人数据（先尝试residents键名，再尝试elderOptions键名）
    let storedElders = uni.getStorageSync('residents');
    
    if (storedElders && storedElders.length > 0) {
      // 如果从residents中获取到了数据
      elderOptions.value = storedElders;
    } else {
      // 尝试从elderOptions中获取数据（兼容旧版）
      storedElders = uni.getStorageSync('elderOptions');
      if (storedElders) {
        elderOptions.value = JSON.parse(storedElders);
      }
    }
    
    // 如果有入住人，默认选择第一个
    if (elderOptions.value.length > 0) {
      elderIndex.value = 0;
      checkinData.elderId = elderOptions.value[0].id;
      checkinData.elderName = elderOptions.value[0].name;
    } else {
      // 如果没有入住人，显示弹窗
      console.log('没有入住人记录，准备显示添加入住人弹窗');
      
      // 使用setTimeout确保DOM已经渲染完成
      setTimeout(() => {
        showAddElderPopup();
      }, 500);
    }
  } catch (e) {
    console.error('获取入住人数据失败', e);
    uni.showToast({
      title: '获取入住人数据失败',
      icon: 'none'
    });
  }
};

// 显示新增入住人弹窗
const showAddElderPopup = () => {
  console.log('打开新增入住人弹窗');
  // 先设置状态再操作DOM
  showAddElder.value = true;
  
  // 禁止页面滚动
  document.body.style.overflow = 'hidden';
  
  // 重置表单
  Object.assign(newElder, {
    name: '',
    idCard: '',
    birthDate: '',
    gender: '男',
    phone: '',
    avatar: '',
    relation: '',
    relationCode: ''
  });
  
  // 重置关系选择索引
  relationIndex.value = 0;
  
  // 重置表单位置，确保滚动到顶部
  setTimeout(() => {
    const popupBody = document.querySelector('.popup-body');
    if (popupBody) {
      popupBody.scrollTop = 0;
    }
    
    try {
      // 确保picker能正确显示
      const pickers = document.querySelectorAll('uni-picker');
      pickers.forEach(picker => {
        if(picker) {
          picker.style.zIndex = '999999';
          picker.style.visibility = 'visible';
          picker.style.opacity = '1';
        }
      });
      
      // 处理uni-app原生组件
      if (uni && uni.createSelectorQuery) {
        uni.createSelectorQuery()
          .selectAll('.uni-picker-container')
          .fields({ node: true, size: true }, (res) => {
            if (res && res.length > 0) {
              res.forEach(item => {
                if (item && item.node) {
                  item.node.style.zIndex = '999999';
                  item.node.style.visibility = 'visible';
                  item.node.style.opacity = '1';
                }
              });
            }
          })
          .exec();
      }
    } catch (e) {
      console.error('处理选择器样式失败', e);
    }
    
    console.log('弹窗已打开');
  }, 300);
};
</script>

<style lang="scss">
// 页面基础层级控制，确保正确的显示顺序
page {
  height: 100%;
  position: relative;
  z-index: 1;
}

.checkin-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8fbfb;
  position: relative;
  z-index: 1;
  
  // 顶部导航
  .nav-header {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
    background-color: #fff;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    position: relative;
    flex-shrink: 0;
    
    .back-btn {
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .iconfont {
        font-size: 20px;
        color: #333;
      }
    }
    
    .page-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
    
    .placeholder {
      width: 30px;
    }
  }
  
  // 养老院信息卡片
  .home-card {
    margin: 15px;
    padding: 16px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    flex-shrink: 0;
    
    .home-name {
      font-size: 18px;
      font-weight: 600;
      color: #2c7873;
      margin-bottom: 10px;
    }
    
    .address-row {
      display: flex;
      align-items: flex-start;
      
      .address-icon {
        font-size: 16px;
        color: #999;
        margin-right: 6px;
        margin-top: 2px;
      }
      
      .address-text {
        font-size: 14px;
        color: #666;
        line-height: 1.4;
        flex: 1;
        word-break: break-all;
      }
    }
  }
  
  // 入住人选择器
  .resident-selector {
    margin: 15px;
    padding: 16px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    flex-shrink: 0;
    
    .selector-scroll {
      display: flex;
      width: 100%;
      overflow-x: auto;
      scrollbar-width: none; /* Firefox */
      -ms-overflow-style: none; /* IE and Edge */
      
      &::-webkit-scrollbar {
        display: none; /* Chrome, Safari, Opera */
      }
      
      .resident-item {
        display: inline-block;
        margin-right: 30px;
        text-align: center;
        position: relative;
        
        &.active {
          &:after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 50%;
            transform: translateX(-50%);
            width: 20px;
            height: 3px;
            background-color: #2c7873;
            border-radius: 2px;
          }
          
          .resident-avatar {
            border-color: #2c7873;
          }
          
          .resident-name {
            color: #2c7873;
            font-weight: 600;
          }
        }
        
        .resident-avatar {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          margin-bottom: 8px;
          border: 2px solid #eee;
          transition: all 0.3s ease;
          background-color: #f8f8f8;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
          overflow: hidden;
          
          image {
            width: 100%;
            height: 100%;
            display: block;
          }
        }
        
        .add-avatar {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          margin-bottom: 8px;
          background-color: #f8f8f8;
          border: 2px dashed #ddd;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .iconfont {
            font-size: 28px;
            color: #999;
          }
        }
        
        .resident-name {
          font-size: 14px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          max-width: 70px;
        }
        
        &:last-child {
          margin-right: 0;
        }
        
        &:active {
          opacity: 0.7;
        }
      }
    }
  }
  
  // 表单滚动区域
  .form-scroll {
    flex: 1;
    overflow: hidden;
  }
  
  // 表单区域
  .form-container {
    padding: 0 15px 20px;
    
    // 表单分段
    .form-section {
      margin-bottom: 20px;
      padding: 20px 16px;
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .section-title {
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        
        &:before, &:after {
          content: '';
          height: 1px;
          background-color: rgba(44, 120, 115, 0.1);
          flex: 1;
        }
        
        .title-text {
          font-size: 16px;
          font-weight: 600;
          color: #2c7873;
          margin: 0 15px;
        }
      }
      
      // 费用选项样式
      .fee-options {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        gap: 10px;
        
        .fee-option-btn {
          flex: 1;
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 16px 10px;
          background-color: #fff;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
          border: 1px solid #ebeef5;
          transition: all 0.3s ease;
          
          &:active {
            transform: scale(0.96);
            background-color: #f9fbfb;
          }
          
          .option-icon {
            width: 54px;
            height: 54px;
            border-radius: 27px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
            
            .iconfont {
              font-size: 26px;
              color: #fff;
            }
            
            &.room-icon {
              background: linear-gradient(135deg, #58c4bd, #2c7873);
              box-shadow: 0 4px 8px rgba(44, 120, 115, 0.2);
            }
            
            &.food-icon {
              background: linear-gradient(135deg, #ffae6d, #f79649);
              box-shadow: 0 4px 8px rgba(247, 150, 73, 0.2);
            }
            
            &.special-icon {
              background: linear-gradient(135deg, #7d97e6, #5269c2);
              box-shadow: 0 4px 8px rgba(82, 105, 194, 0.2);
            }
          }
          
          .option-info {
            width: 100%;
            text-align: center;
            
            .option-name {
              font-size: 15px;
              font-weight: 600;
              color: #333;
              margin-bottom: 6px;
              
              &.required:after {
                content: '*';
                color: #ff6b6b;
                margin-left: 2px;
              }
            }
            
            .option-status {
              font-size: 13px;
              color: #888;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              max-width: 100%;
            }
          }
        }
      }
      
      .form-item {
        margin-bottom: 20px;
        position: relative;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 15px;
          font-weight: 500;
          color: #333;
          margin-bottom: 12px;
          display: flex;
          align-items: center;
          
          &.required:after {
            content: '*';
            color: #ff6b6b;
            margin-left: 4px;
          }
        }
        
        .input-wrapper {
          position: relative;
          width: 100%;
          
          .input-icon, .calendar-icon, .arrow-icon, .add-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 16px;
            color: #aaa;
            z-index: 1;
          }
          
          .add-btn {
            position: absolute;
            right: 0;
            top: 0;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2;
            
            .iconfont {
              font-size: 18px;
              color: #2c7873;
            }
          }
          
          .placeholder {
            color: #aaa;
          }
        }
        
        .input, .picker-value {
          width: 100%;
          height: 48px;
          background-color: #f8fbfb;
          border-radius: 10px;
          padding: 0 15px;
          font-size: 15px;
          color: #333;
          border: 1px solid #e6eaea;
          transition: all 0.3s ease;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          
          &:focus {
            border-color: #2c7873;
            box-shadow: 0 0 0 2px rgba(44, 120, 115, 0.1);
          }
        }
        
        .textarea {
          width: 100%;
          height: 100px;
          background-color: #f8fbfb;
          border-radius: 10px;
          padding: 12px 15px;
          font-size: 15px;
          color: #333;
          border: 1px solid #e6eaea;
          transition: all 0.3s ease;
          box-sizing: border-box;
          line-height: 1.5;
          
          &:focus {
            border-color: #2c7873;
            box-shadow: 0 0 0 2px rgba(44, 120, 115, 0.1);
          }
        }
        
        .picker-value {
          position: relative;
          z-index: 1;
          padding-right: 40px;
          justify-content: space-between;
          
          .placeholder-text {
            color: #aaa;
          }
          
          .value-text {
            color: #333;
            font-weight: 500;
          }

          .calendar-icon {
            position: absolute;
            right: 15px;
            z-index: 1;
          }
        }
      }
    }
    
    // 费用总结部分
    .price-summary {
      margin-bottom: 20px;
      padding: 20px 16px;
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .summary-title {
        font-size: 17px;
        font-weight: 600;
        color: #333;
        margin-bottom: 16px;
        text-align: center;
        position: relative;
        
        &:after {
          content: '';
          position: absolute;
          left: 50%;
          bottom: -6px;
          width: 40px;
          height: 3px;
          background-color: rgba(44, 120, 115, 0.2);
          border-radius: 3px;
          transform: translateX(-50%);
        }
      }
      
      .summary-list {
        display: flex;
        flex-direction: column;
        gap: 14px;
        
        .summary-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .item-name {
            font-size: 15px;
            color: #555;
          }
          
          .item-price {
            font-size: 15px;
            color: #333;
            font-weight: 500;
          }
        }
        
        .summary-divider {
          height: 1px;
          background-color: #eee;
          margin: 8px 0;
        }
        
        .total-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 8px;
          
          .total-label {
            font-size: 17px;
            font-weight: 600;
            color: #333;
          }
          
          .total-value {
            font-size: 22px;
            font-weight: 700;
            color: #ff6b6b;
            text-shadow: 0 1px 0 rgba(0, 0, 0, 0.05);
          }
        }
      }
    }
  }
  
  // 底部操作栏
  .bottom-bar {
    padding: 15px;
    background-color: #fff;
    border-top: 1px solid #eee;
    flex-shrink: 0;
    
    .submit-btn {
      width: 100%;
      height: 50px;
      background: linear-gradient(135deg, #419b94, #2c7873);
      border-radius: 25px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4px 12px rgba(44, 120, 115, 0.2);
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;
      
      &:before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0));
        opacity: 0;
        transition: opacity 0.3s ease;
      }
      
      &.active:before {
        opacity: 1;
      }
      
      text {
        font-size: 16px;
        font-weight: 600;
        color: #fff;
        letter-spacing: 1px;
        position: relative;
        z-index: 1;
      }
      
      &:active {
        transform: translateY(2px);
        box-shadow: 0 2px 6px rgba(44, 120, 115, 0.2);
      }
    }
  }
  
  // 禁止页面滚动样式
  &.no-scroll {
    overflow: hidden;
    height: 100vh;
    
    .form-scroll {
      overflow: hidden;
    }
  }
}

// 新增入住人弹窗样式
.add-elder-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99999 !important;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
  }
  
  .popup-content {
    width: 85%;
    max-width: 340px;
    background-color: #fff;
    border-radius: 12px;
    overflow: hidden;
    position: relative;
    z-index: 10;
    animation: popup-in 0.3s ease-out;
    display: flex;
    flex-direction: column;
    max-height: 85vh;
    
    @keyframes popup-in {
      0% {
        opacity: 0;
        transform: scale(0.9);
      }
      100% {
        opacity: 1;
        transform: scale(1);
      }
    }
  }
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #e0e0e0;
    flex-shrink: 0;
    
    .popup-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
    
    .close-btn {
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .iconfont {
        font-size: 20px;
        color: #999;
      }
    }
  }
  
  .popup-body {
    padding: 15px;
    overflow-y: auto;
    flex: 1;
    
    .avatar-selector {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 20px;
      
      .avatar-preview {
        width: 80px;
        height: 80px;
        border-radius: 40px;
        overflow: hidden;
        position: relative;
        margin-bottom: 10px;
        border: 2px solid #e8f4f2;
        box-shadow: 0 4px 12px rgba(44, 120, 115, 0.15);
        transition: all 0.3s ease;
        
        image {
          width: 100%;
          height: 100%;
          transition: transform 0.3s ease;
        }
        
        .avatar-mask {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(44, 120, 115, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: all 0.3s ease;
          
          .iconfont {
            font-size: 26px;
            color: #fff;
          }
        }
        
        &:active {
          transform: scale(0.95);
          
          .avatar-mask {
            opacity: 1;
          }
          
          image {
            transform: scale(1.05);
          }
        }
      }
      
      .avatar-tip {
        font-size: 12px;
        color: #999;
      }
    }
    
    .popup-form-item {
      margin-bottom: 15px;
      
      .popup-label {
        font-size: 15px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
        
        &.required:after {
          content: '*';
          color: #ff6b6b;
          margin-left: 4px;
        }
      }
      
      .popup-input {
        width: 100%;
        height: 44px;
        background-color: #f8fbfb;
        border-radius: 8px;
        padding: 0 12px;
        font-size: 15px;
        color: #333;
        border: 1px solid #e6eaea;
        box-sizing: border-box;
      }
      
      .popup-picker {
        width: 100%;
        height: 44px;
        background-color: #f8fbfb;
        border-radius: 8px;
        padding: 0 12px;
        font-size: 15px;
        color: #333;
        border: 1px solid #e6eaea;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;
        
        .placeholder-text {
          color: #aaa;
        }
        
        .value-text {
          color: #333;
          flex: 1;
        }
        
        .arrow-icon {
          position: absolute;
          right: 12px;
          top: 50%;
          transform: translateY(-50%);
          font-size: 16px;
          color: #aaa;
        }
        
        .picker-inner {
          display: flex;
          width: 100%;
          align-items: center;
          
          .value-text {
            flex: 1;
            font-size: 14px;
            color: #333;
          }
          
          .placeholder-text {
            flex: 1;
            font-size: 14px;
            color: #999;
          }
          
          .arrow-icon {
            font-size: 12px;
            color: #999;
            position: static;
            transform: none;
          }
        }
      }
      
      .radio-group {
        display: flex;
        flex-wrap: wrap;
        
        .radio-label {
          display: flex;
          align-items: center;
          margin-right: 30px;
          
          text {
            font-size: 15px;
            color: #333;
            margin-left: 4px;
          }
        }
      }
    }
  }
  
  .popup-footer {
    display: flex;
    border-top: 1px solid #eee;
    flex-shrink: 0;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      font-weight: 500;
      
      &:active {
        opacity: 0.8;
      }
    }
    
    .cancel-btn {
      color: #666;
      background-color: #f5f5f5;
    }
    
    .confirm-btn {
      color: #fff;
      background-color: #999;
      
      &.active {
        background-color: #2c7873;
      }
    }
  }
}

// 费用选项弹窗样式
.fee-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
    touch-action: none; // 阻止触摸事件向下传递
  }
  
  .popup-content {
    width: 80%; // 减小弹框宽度
    max-width: 340px; // 减小最大宽度
    max-height: 80vh;
    background-color: #fff;
    border-radius: 16px;
    position: relative;
    z-index: 2;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    animation: popup-in 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    touch-action: pan-y; // 只允许垂直方向的滚动
    
    @keyframes popup-in {
      0% {
        opacity: 0;
        transform: scale(0.95);
      }
      100% {
        opacity: 1;
        transform: scale(1);
      }
    }
    
    &.popup-rooms {
      border-top: 4px solid #2c7873;
    }
    
    &.popup-food {
      border-top: 4px solid #f79649;
    }
    
    &.popup-special {
      border-top: 4px solid #5269c2;
    }
  }
  
  .popup-header {
    padding: 18px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;
    
    .popup-title {
      font-size: 20px;
      font-weight: 600;
      color: #333;
    }
    
    .close-btn {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      
      .iconfont {
        font-size: 20px;
        color: #999;
      }
      
      &:active {
        background-color: #f5f5f5;
      }
    }
  }
  
  .popup-body {
    flex: 1;
    max-height: calc(80vh - 122px);
    overflow-y: auto;
    padding: 16px 8px; // 进一步减小内边距
    -webkit-overflow-scrolling: touch;
    
    .option-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .option-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px;
        background-color: #f8fbfb;
        border-radius: 10px;
        border: 1px solid #e6eaea;
        transition: all 0.3s ease;
        
        &.selected {
          border-color: #2c7873;
          background-color: rgba(44, 120, 115, 0.05);
        }
        
        .option-content {
          flex: 1;
          
          .option-name {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin-bottom: 6px;
            display: flex;
            align-items: center;
          }
          
          .option-price {
            font-size: 18px;
            font-weight: 600;
            color: #ff6b6b;
            margin-bottom: 6px;
            
            .price-unit {
              font-size: 14px;
              font-weight: 400;
              color: #999;
              margin-left: 2px;
            }
          }
          
          .option-note {
            font-size: 13px;
            color: #666;
            background-color: rgba(44, 120, 115, 0.05);
            border-radius: 4px;
            padding: 4px 8px;
            display: inline-block;
            margin-top: 2px;
          }
        }
        
        .option-check {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          border: 1px solid #ddd;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #fff;
          margin-left: 10px;
          flex-shrink: 0;
          
          .check-icon {
            font-size: 16px;
            color: #2c7873;
          }
        }
        
        &:active {
          transform: scale(0.98);
        }
      }
    }
  }
  
  .popup-footer {
    display: flex;
    border-top: 1px solid #f0f0f0;
    height: 56px;
    flex-shrink: 0;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 17px;
      font-weight: 500;
      transition: all 0.2s ease;
      
      &:active {
        opacity: 0.8;
      }
    }
    
    .cancel-btn {
      color: #666;
      background-color: #f7f7f7;
    }
    
    .confirm-btn {
      color: #fff;
      background-color: #2c7873;
      
      &:active {
        background-color: #266a66;
      }
    }
  }
}

// 修复选择器显示层级问题
:deep(.uni-picker-container),
:deep(.uni-picker),
:deep(.uni-picker-view-wrapper),
:deep(.uni-picker-content),
:deep(uni-picker) {
  z-index: 9000 !important;
}

// 当新增入住人弹窗显示时，调整选择器样式
.add-elder-popup {
  :deep(.uni-picker-container),
  :deep(.uni-picker),
  :deep(.uni-picker-view-wrapper),
  :deep(.uni-picker-content),
  :deep(uni-picker) {
    z-index: 999999 !important;
  }
}

// 选择器样式覆盖
:deep(.uni-picker),
:deep(.uni-picker-view) {
  visibility: visible !important;
  opacity: 1 !important;
}

// 特殊处理与账号关系选择器
.relation-item {
  position: relative;
  z-index: 1000;
  
  .relation-picker {
    position: relative;
    z-index: 10001;
  }
  
  .popup-picker {
    position: relative;
    z-index: 10001;
  }
}

// 调整入住日期选择框的层级，确保不会超过弹窗
:deep(uni-picker[mode="date"]) {
  z-index: 8000 !important;
}

// 确保弹窗内的日期选择器正确显示
.add-elder-popup {
  :deep(uni-picker[mode="date"]) {
    z-index: 999999 !important;
  }
}
</style> 